<template>
  <div class="container">
    <div class="el_card_body">
      <!-- 下面表格table -->
    <el-card v-loading="loading">
          <div v-if="$route.query.id&&$route.query.subjectName">
  <el-breadcrumb separator-class="el-icon-arrow-right">
  <el-breadcrumb-item>学科管理</el-breadcrumb-item>
  <el-breadcrumb-item>{{$route.query.subjectName}}</el-breadcrumb-item>
  <el-breadcrumb-item>标签管理</el-breadcrumb-item>
</el-breadcrumb>
      </div>
      <el-divider v-if="$route.query.id&&$route.query.subjectName"></el-divider>
      <!-- 搜索input -->
      <el-row type="flex" justify="space-around" align="middle">
      <!-- 左 -->
        <el-col>
          标签名称  <el-input v-model="input" style="width:150px;margin-right:30px"/>
          状态  <el-select  v-model="value" style="width:150px;margin-right:15px" placeholder="请选择">
                  <el-option v-for="item in options" :key="item" :value="item">{{ item }}</el-option>
               </el-select>
             <el-button @click="clearFn()">清除</el-button>
            <el-button type="primary" @click="searchFn()">搜索</el-button>
        </el-col>
      <!-- 右 -->

      <el-col style="text-align: right;margin-top: 20px;">
        <el-button type="text"
        v-if="$route.query.id&&$route.query.subjectName"
          icon="el-icon-back"
          @click="$router.back()">返回学科</el-button>
            <el-button type="success" icon="el-icon-edit" @click="addFn()">新增标签
            </el-button>
       </el-col>
      </el-row>
      <!-- 提示 -->
       <el-alert style="margin-bottom: 15px"
    type="info"
    :closable="false"
    show-icon>
     <template > 数据一共{{ page.total }}条</template>
          </el-alert>
      <el-table :data="list">
        <el-table-column label="序号"  type="index" align="center" />
        <el-table-column label="所属学科"  prop="subjectName" align="center" />
        <el-table-column label="标签名称" prop="tagName"  align="center"/>
        <el-table-column label="创建者"  prop="username" align="center" />
        <el-table-column label="创建日期"  prop="addDate" align="center">
          <template v-slot="{row}">{{ row.addDate|parseTimeByString }}</template>
        </el-table-column>
        <el-table-column label="状态"  prop="state" align="center">
            <template v-slot="{row}">
              <span v-if="row.state===1">已禁用</span>
              <span v-else>已启用</span>
            </template>
        </el-table-column>
        <el-table-column label="操作"  fixed="right" width="280" align="center">
           <template v-slot="{row}">
              <el-button  type="text" @click="changeStateFn(row)">
                <span v-if="row.state===1">启用</span>
                <span v-else>禁用</span>
              </el-button>
                <el-button type="text" @click="updateFn(row)" :disabled='row.state!==0'>修改</el-button>
              <el-button
              type="text"
              :disabled='row.state!==0'
                @click="removeFn(row)"
              >删除</el-button>
            </template>
        </el-table-column>
      </el-table>
      <!-- 分页组件 -->
      <el-row type="flex" justify="end" align="middle" style="height: 60px">
        <el-pagination
         background
      @size-change="handleSizeChange"
      @current-change="changePge"
      :current-page="page.page"
      :page-sizes="[5,10,20,50]"
      :page-size="page.pagesize"
      layout="  prev, pager, next, sizes,jumper"
      :total="page.total"
    >
    </el-pagination>
      </el-row>
    </el-card>
  </div>
  <!-- 修改弹层 -->
  <el-dialog class="show_dialog"
      v-bind="$attrs"
      :title="showTitle"
      :visible="showDialog"
      v-on="$listeners"
      @open="onOpen"
      @close="onClose"

    >
      <el-form
        ref="formDataRef"
        :model="formData"
        :rules="rules"
        size="medium"
        label-width="100px"
      >
        <el-form-item label="所属学科" prop="subjectID" v-if="!$route.query.id&&!$route.query.subjectName">
          <el-select
            v-model="formData.subjectID"
            clearable
            style="width:300px;"
          >
         <el-option
              v-for="(item, index) in subjectOptions"
              :key="index"
              :label="item.label"
              :value="item.value"
              :disabled="item.disabled"
            ></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="目录名称" prop="tagName">
          <el-input
            v-model="formData.tagName"
            placeholder="1-50个字符"
            clearable
            style="width:300px;"
          >
          </el-input>
        </el-form-item>

      </el-form>
      <div slot="footer" type="flex" justify="center" align="center">
        <el-button @click="close">取消</el-button>
        <el-button type="primary" @click="handelConfirm">确定</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import { list, remove, update, detail, add, changeState } from '@/api/hmmm/tags'
import { simple } from '@/api/hmmm/subjects'
import { list as questionList } from '@/api/hmmm/questions'
export default {
  name: '',
  props: {},
  data () {
    return {
      formData: {
        subjectID: undefined, // 学科id
        subjectName: undefined, // 所属学科
        tagName: undefined // 目录名称
      },
      rules: {
        // 所属学科（subjectName）：必填 1-50个字符  / 同级部门中禁止出现重复
        subjectName: [{
          required: true,
          message: '请输入所属学科',
          trigger: 'blur'
        }],
        // 目录名称（tagName）：必填 1-50个字符  / 不允许重复
        tagName: [{
          required: true,
          message: '请输入目录名称',
          trigger: 'blur'
        }]
      },
      subjectOptions: [], // 所有学科列表
      input: '',
      options: ['启用', '禁用'],
      value: '',
      loading: false,
      page: {
        page: 1, // 当前页,
        pages: null, // 总页数
        pagesize: 10, // 每页几条数据
        total: null// 总条数
      },
      list: [], // 表格数组
      showDialog: false, // 修改弹层
      subjectID: null,
      id: null, // 数据id
      stateText: '禁用',
      status: null,
      searchData: { // 搜索目标
        page: null,
        pagesize: null,
        subjectID: null,
        tagName: null,
        state: null
      },
      searchState: 1 // 判断是否在搜索列表
    }
  },
  created () {
    this.getSubjectListFn()
    this.getOptionsFn()
    this.getQuestionFn()
    console.log(this.$route.query.id)
  },
  methods: {
    // 清除搜索
    clearFn () {
      this.input = ''
      this.value = ''
      this.getSubjectListFn()
    },
    // 搜索
    async searchFn () {
      if (!this.value && !this.input) {
        this.$message('请输入搜索信息！')
      } else {
        if (this.$route.query.id) {
          // 跳转过来的
          this.a = 2
          // 1.开启loading
          this.loading = true
          if (this.value === '禁用') {
            this.searchData.state = 1
          } else {
            this.searchData.state = 0
          }
          this.searchData.subjectID = this.$route.query.id
          this.searchData.tagName = this.input// 搜索的标签名称-tagName
          this.searchData.pagesize = this.page.pagesize// 搜索的每页数量-pagesize
          this.searchData.page = this.page.page// 搜索的页码-page
          // 2.请求接口，获取列表
          const { data } = await list(this.searchData)
          this.page.total = data.counts
          this.list = data.items
          // 3.关闭loading
          this.loading = false
          this.searchState = 2// 搜索状态state
        } else {
          // 1.开启loading
          this.loading = true
          if (this.value === '禁用') {
            this.searchData.state = 1
          } else {
            this.searchData.state = 0
          }
          this.searchData.tagName = this.input// 搜索的标签名称-tagName
          this.searchData.pagesize = this.page.pagesize// 搜索的每页数量-pagesize
          this.searchData.page = this.page.page// 搜索的页码-page
          // 2.请求接口，获取列表
          const { data } = await list(this.searchData)
          this.page.total = data.counts
          this.list = data.items
          // 3.关闭loading
          this.loading = false
          this.searchState = 2// 搜索状态state
        }
      }
    },
    // 点击状态切换（1启用，0禁用）
    async changeStateFn (val) {
      // 判断是在禁用状态（state === 0）还是启用状态（state === 1）
      if (val.state === 1) {
        val.state = 0
        this.status = '禁用'
      } else {
        val.state = 1
        this.status = '启用'
      }
      var data = {
        id: val.id,
        state: val.state
      }
      try {
        await changeState(data)
        this.$message.success('操作成功！')
      } catch (err) {
        this.$message('操作失败！')
      }
    },
    // 切换每页多少条
    handleSizeChange (val) {
      this.page.pagesize = val
      this.getSubjectListFn()
    },
    // 点击页码显示相应内容
    changePge (val) {
      // 判断是否在搜索情况下
      if (this.a === 1) {
        // 所有数据下
        this.page.page = val
        this.getSubjectListFn()
      } else if (this.$route.query.id) {
        // this.a = 2
        // 表示跳转过来的情况下
        this.page.page = val
        this.getSubjectListFn()
      } else {
        // 搜索状态
        this.page.page = val
        this.searchFn()
      }
    },
    // 获取基础题库列表----subjectID
    async getQuestionFn () {
      const res = await questionList()
      this.subjectID = res.data.items.subjectID
      this.formData.subjectID = res.data.items.subjectID
    },
    // 新增
    async addFn () {
      // 1.开启loading
      this.loading = true
      // 2.显示弹层
      this.showDialog = true
      // 3.关闭loading
      this.loading = false
      // 4.线上接口拿所有学科选项subjectoption
      const { data } = await simple()
      this.subjectOptions = data
    },
    // 获取下拉所属学科列表
    async getOptionsFn () {
      // 下拉选项
      const { data } = await simple()
      this.subjectOptions = data
    },
    // 获取所有列表
    async getSubjectListFn () {
      // 1.开启loading
      this.loading = true
      // this.page.subjectID = this.$route.query.id || null （跳转过来情况下）
      if (this.$route.query.id) {
        this.page.subjectID = this.$route.query.id
        this.a = 2
      }
      // 2.请求接口，获取列表
      const { data } = await list(this.page)
      this.list = data.items
      this.page.total = data.counts
      this.id = data.items.id
      // 3.关闭loading
      this.loading = false
    },
    // 删除标签
    async removeFn (data) {
      try {
        // 1.确定删除吗
        await this.$confirm('确认删除吗？')
        // 2.接口删除
        await remove(data)
        // 3.提示文字
        this.$message.success('删除成功！')
        // 4.刷新列表
        this.getSubjectListFn()
      } catch (error) {
        this.$message('取消删除！')
      }
    },
    // 修改标签
    async updateFn (data1) {
      // 1.开启loading
      this.loading = true
      // 2.显示弹层
      this.showDialog = true
      // 3.关闭loading
      this.loading = false
      // 4.回显数据
      const { data } = await detail(data1)
      this.formData = data
    },
    onOpen () {},
    // 6.右上角关闭
    onClose () {
      // 1.重置校验字段
      this.$refs.formDataRef.resetFields()
      // 2.清除、初始化formData里的数据
      this.formData = this.$options.data().formData
      // 3.关闭弹层
      this.showDialog = false
    },
    // 5.取消
    close () {
      this.showDialog = false
    },
    // 4.确认
    handelConfirm () {
      // 1.校验表单
      this.$refs.formDataRef.validate(async valid => {
        if (!valid) return
        // 判断是不是跳转过来的
        if (this.$route.query.id) {
        // 2.通过校验，上传数据update
          if (this.formData.id) {
          // 如果能进if表示有id，是编辑
            await update(this.formData)
          } else {
          // 没有id,是新增
            this.formData.subjectID = this.$route.query.id
            await add(this.formData)
          }
          // 3.成功提示文字
          this.$message.success('操作成功！')
          // 4.重新获取最新列表
          this.getSubjectListFn()
          // 5.关闭弹层
          this.close()
        } else {
          //  2.通过校验，上传数据update
          if (this.formData.id) {
          // 如果能进if表示有id，是编辑
            await update(this.formData)
          } else {
          // 没有id,是新增
            await add(this.formData)
          }
          // 3.成功提示文字
          this.$message.success('操作成功！')
          // 4.重新获取最新列表
          this.getSubjectListFn()
          // 5.关闭弹层
          this.close()
        }
      })
    }

  },
  computed: {
    // 有无id来动态决定展示title是编辑(有)还是新增（没有）
    showTitle () {
      return this.formData.id ? '修改目录' : '新增目录'
    }
  },
  watch: {},
  components: {}
}
</script>

<style lang="less" scoped>
.el_card_body {
  padding: 20px;
}
.show_dialog {
  width: 930px;
  margin: auto;
}
</style>
